const fs = require('fs');
const path = require('path');

function startup() {
    return new Promise((resolve, reject) => {
        try {
            var express = require('express');
            var http = require('http');
            var https = require('https');
            var app = express();
            var bodyParser = require('body-parser');
            var compression = require('compression');
            var envConf = require('../config/env');
            console.log(`env config:${JSON.stringify(envConf)}`);

            require('./models').init({ canCreateTables: true }).then(() => {
                //设置express基础设施
                app.disable('x-powered-by');
                app.use(compression());
                app.use(bodyParser.json()); // for parsing application/json
                app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

                //setup session provider
                let session = require('express-session');
                let FileStore = require('session-file-store')(session);
                app.use(session({
                    store: new FileStore({
                        ttl: 7200,
                        path: envConf.session.args.path,
                    }),
                    secret: 'mss-X5PZ-PHMF-93ON-LPZQ'
                }));

                require('./routers')(app, express);

                //extra mime-types support
                let mime = require('mime');
                mime.define({
                    'application/font-woff2': ['ttf'],
                });

                var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080,
                    ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
                http.createServer(app).listen(port, ip, function () {
                    console.log(`Application worker pid=${process.pid} started...@${ip}:${port}`);
                });
                require('./business').onStartup();
                resolve();
            }).catch(err => reject(err));
        } catch (err) {
            console.error(err);
            reject(err);
        }
    });
}

// 启动及端口
module.exports = startup;